<?php


namespace app\admin\controller\chel;

use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;
use think\facade\Db;

/**
 * @ControllerAnnotation(title="盘点")
 */
class Checklist extends AdminController
{

    use \app\admin\traits\Curd;
    protected $sort = [
        'id'   => 'desc',
    ];

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new \app\admin\model\Checklist();
        
    }
    
    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            $param = $this->request->param();
           
            list($page, $limit, $where) = $this->buildTableParames();

            $where = [];
            if(!empty($param['check_no']) && isset($param['check_no']))
            {
                $where[] = [
                    ['check_no', '=', $param['check_no']],
                ];
            }
      
            if(!empty($param['status_time']) && !empty($param['end_time']))
            {
                $where[] = [
                    ['create_time', 'between', [$param['status_time'],$param['end_time']]],
                ];
            }
            $count = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
                foreach ($list as $k => $v){
                    //分类
                    $good_type = Db::name('good_type')->where('id',$v['good_type_id'])->field('title')->find();
                    if(empty($good_type)){
                        $v['good_type_name'] = "";
                    }else{
                        $v['good_type_name'] = $good_type['title'];
                    }
                    $admin = Db::name("system_admin")->where("id",$v["outbound_uid"])->find();
                    if(!empty($admin["employee_name"])){
                        $v["employee_name"] = $admin["employee_name"];
                    }else{
                        $v["employee_name"] ="";
                    }

                    $list[$k] = $v;
                }
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        $good_type = Db::name("good_type")->order("id desc")->select()->toArray();
        $this->assign("good_type",$good_type);
        return $this->fetch();
    }


    /**
    * @NodeAnotation(title="添加")
    */
    public function add()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->param();
            if(empty($post['check_no'])){
                $this->error('盘点单号不能为空');
            }
            if(empty($post['check_name'])){
                $this->error('盘点单名称不能为空');
            }
            if(empty($post['outbound_name'])){
                $this->error('仓库人名称不能为空');
            }
            if(empty($post['outbound_uid'])){
                $this->error('仓库人id不能为空');
            }
           
            if(empty($post['goodsc_item'])){
                $this->error('盘点商品不能为空');
            }
            $goodsc_item = $post['goodsc_item'];
            $data = [
                'check_no'=>$post['check_no'],
                'check_name'=>$post['check_name'],
                'outbound_name'=>$post['outbound_name'],
                'outbound_uid'=>$post['outbound_uid'],
                'create_time'=>time()
            ];
            try {
                $save = Db::name("checklist")->insert($data);
                $checklist_id = Db::name('checklist')->getLastInsID();
                //添加入库商品信息 
                foreach($goodsc_item as $k=>$v){
                    $v["checklist_id"] = $checklist_id;
                    $goodsc_item[$k] = $v;
                }
                Db::name('checklist_item')->insertAll($goodsc_item); 

            } catch (\Exception $e) {
                $this->error('保存失败:' . $e->getMessage());
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }else{
            return $this->fetch();
        }
       
    }

    //盘点编辑
    public function upedit(){
        if ($this->request->isAjax()) {
            $post = $this->request->param();
            if(empty($post['checklist_id'])){
                $this->error('盘点id不能为空');
            } 
            if(empty($post['check_no'])){
                $this->error('盘点单号不能为空');
            }
            if(empty($post['check_name'])){
                $this->error('盘点单名称不能为空');
            }
            if(empty($post['outbound_name'])){
                $this->error('仓库人名称不能为空');
            }
            if(empty($post['outbound_uid'])){
                $this->error('仓库人id不能为空');
            }
           
            if(empty($post['goodsc_item'])){
                $this->error('盘点商品不能为空');
            }
            $goodsc_item = $post['goodsc_item'];
           
            $data = [
                'check_no'=>$post['check_no'],
                'check_name'=>$post['check_name'],
                'outbound_name'=>$post['outbound_name'],
                'outbound_uid'=>$post['outbound_uid']
            ];
            try {
                Db::name("checklist")->where("id",$post["checklist_id"])->update($data);
                Db::name('checklist_item')->where("checklist_id",$post["checklist_id"])->delete();
                //添加入库商品信息 
                foreach($goodsc_item as $k=>$v){
                    $v["checklist_id"] = $post["checklist_id"];
                    $goodsc_item[$k] = $v;
                }
                Db::name('checklist_item')->insertAll($goodsc_item); 
            
            } catch (\Exception $e) {
                $this->error('保存失败:' . $e->getMessage());
            }
            $this->success('保存成功');
        }else{
            return $this->fetch();
        }
    }


    //新建盘点基础数据
    public function pdincoming_data(){
        $session = session("admin");
        //盘点单号
        $check_no = date('Ymd') . substr(implode(null, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8).$session['id'];

        $outbound_name = $session["employee_name"];//盘点人姓名
        $outbound_uid = $session["id"];//盘点人id
        
        $res = [
            "check_no"=>$check_no,
            "outbound_name"=>$outbound_name,
            "outbound_uid"=>$outbound_uid,
        ];
        return json([
            "code"=>1,
            "data"=>$res
        ]);
    }


     /**
    * @NodeAnotation(title="开始盘点和继续盘点")
    */
    public function edit()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->param();
            if(empty($post['checklist_id'])){
                $this->error('盘点id不能为空');
            }  
            if(empty($post['goodsc_item'])){
                $this->error('盘点商品不能为空');
            }
            if(empty($post['status'])){
                $this->error('状态不能为空');
            }
            $goodsc_item = $post['goodsc_item'];
            // $goodsc_item = [
            //     [
            //         "chitem_id"=>"盘点详情id",
            //         "physical_inventory"=>"实际库存",
            //         "remarks"=>"备注",
            //         "check_no"=>"盘点单号",
            //         "gid"=>"商品id",
            //         "good_type_id"=>"商品分类id",
            //         "good_type_name"=>"商品分类名称",
            //         "stock"=>"库存",
            //         "receipt_issue_num"=>"出入库数量"
            //     ]
            // ];
            foreach($goodsc_item as $k=>$v){
                Db::name("checklist_item")->where("id",$v["chitem_id"])->update(["physical_inventory"=>$v["physical_inventory"],"remarks"=>$v["remarks"]]);
            }
            $checklist = $this->model->where('id',$post['checklist_id'])->find();
            try {
                 //status 2保存继续盘点  3盘点结束
                if($post['status'] == 2){
                
                    $this->model->where('id',$post['checklist_id'])->update(["status"=>2]);
                }elseif($post['status'] == 3){
                    foreach($goodsc_item as $k=>$v){
                        if($v["physical_inventory"] < $v["stock"]){
                            $receipt_issue_type = 5;//盘亏出库
                            $numcr = bcsub($v["stock"],$v["physical_inventory"]);
                            //修改商品库存
                            Db::name("goods")->where("id",$v["gid"])->dec("stock",$numcr)->update();
                              //添加出入库明细
                            $data_crk = [
                                "data_id"=>$post['checklist_id'],//数据id
                                'odd_numbers'=>$v["check_no"],//单号
                                "gid"=>$v["gid"],
                                "good_type_id"=>$v["good_type_id"],
                                "good_type_name"=>$v["good_type_name"],
                                "receipt_issue_type"=>$receipt_issue_type,//1采购入库 2作废入库 3销售出库 4盘赢入库 5盘亏出库
                                "create_time"=>time(),
                                "remarks"=>$v["remarks"],
                                "discrepancy"=>$checklist["outbound_name"],
                                "receipt_issue_num"=>$numcr //出入库数量
                            ];
                        Db::name("receipt_issue_detailed")->insert($data_crk);
                        }elseif($v["physical_inventory"] > $v["stock"]){
                            $receipt_issue_type = 4;//盘赢入库
                            $numcr = bcsub($v["physical_inventory"],$v["stock"]);
                            //修改商品库存
                            Db::name("goods")->where("id",$v["gid"])->inc("stock",$numcr)->update();
                              //添加出入库明细
                            $data_crk = [
                                "data_id"=>$post['checklist_id'],//数据id
                                'odd_numbers'=>$v["check_no"],//单号
                                "gid"=>$v["gid"],
                                "good_type_id"=>$v["good_type_id"],
                                "good_type_name"=>$v["good_type_name"],
                                "receipt_issue_type"=>$receipt_issue_type,//1采购入库 2作废入库 3销售出库 4盘赢入库 5盘亏出库
                                "create_time"=>time(),
                                "remarks"=>$v["remarks"],
                                "discrepancy"=>$checklist["outbound_name"],
                                "receipt_issue_num"=>$numcr //出入库数量
                            ];
                            Db::name("receipt_issue_detailed")->insert($data_crk);
                        }
                      

                    }
                    $this->model->where('id',$post['checklist_id'])->update(["status"=>3]);
                }

            } catch (\Exception $e) {
                $this->error('保存失败:' . $e->getMessage());
            }
            $this->success('保存成功') ;
        }
        return $this->fetch();
    }

    //盘点详情
    public function chkgoodc_detail(){
        if ($this->request->isAjax()) {
            $post = $this->request->param();
            if(empty($post['checklist_id'])){
                $this->error('盘点不能为空');
            }
            $row = $this->model->where('id',$post['checklist_id'])->find();
            //商品数据
            $checklist_item = Db::name("checklist_item")->where("checklist_id",$post["checklist_id"])->select()->toArray();
           
            foreach ($checklist_item as $k => $v){
                //商品
                $goods = Db::name('goods')->where('id',$v['gid'])->field('title')->find();
                if(empty($goods)){
                    $v['good_name'] = "";
                }else{
                    $v['good_name'] = $goods['title'];
                }

                $checklist_item[$k] = $v;
            }
            $admin = Db::name("system_admin")->where("id",$row["outbound_uid"])->find();
            if(!empty($admin["employee_name"])){
                $row["employee_name"] = $admin["employee_name"];
            }else{
                $row["employee_name"] ="";
            }
            $list = [
                "row"=>$row,
                "checklist_item"=>$checklist_item
            ];
            return json(
                [
                    "code"=>1,
                    "data"=>$list
                ]
            );
        }
    }

    //编辑备注
    public function chkedit_remark(){
        if ($this->request->isAjax()) {
            $post = $this->request->param();
            if(empty($post['reamark'])){
                $this->error('参数不能为空');
            }
            Db::name("checklist")->where("id",$post["id"])->update(["remark"=>$post["reamark"]]);
            $this->success('编辑成功') ;
        }else{
            return $this->fetch();
        }
    }
 
 
} 